package com.example.demo.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.example.demo.domain.entity.TrainClass;
import com.example.demo.domain.entity.TrainCommitRecord;
import com.example.demo.domain.entity.TrainHomework;
import com.example.demo.domain.entity.TrainHomeworkProblem;
import com.example.demo.domain.vo.RepetitionResult;
import com.example.demo.service.TrainCommitRecordService;
import com.example.demo.service.TrainHomeworkService;
import com.example.demo.service.TrainReportService;
import com.example.demo.tool.RepetitionRate;
import com.example.demo.tool.TimeStamp2Date;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liguang03
 * @date 2024/4/7
 */
@Service
@Slf4j
public class TrainReportServiceImpl implements TrainReportService {

    @Resource
    private TrainHomeworkService trainHomeworkService;


    @Resource
    private TrainCommitRecordService trainCommitRecordService;


    @Override
    public void downloadRepCheckReport(TrainClass trainClass, TrainHomeworkProblem trainHomeworkProblem, HttpServletResponse response) throws Exception {
        try {
            TrainHomework trainHomework = trainHomeworkService.getById(trainHomeworkProblem.getHomeworkId());

            response.setHeader("content-Type", "application/vnd.ms-excel");
            // 下载文件的默认名称(设置下载文件的默认名称)
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    new String((trainClass.getName() + "_" + trainHomeworkProblem.getProblemId() + "_" + trainHomework.getTitle()   + "_查重报告").getBytes("gb2312"),
                            "iso8859-1") + ".xls");
            //导出操作
            try {
                Workbook workbook = ExcelExportUtil.exportExcel(
                        new ExportParams(trainHomeworkProblem.getProblemId() + " 题" + trainHomework.getTitle(), trainHomeworkProblem.getProblemId().toString()),
                        RepetitionResult.class,
                        getTcProRepResults(trainClass, trainHomeworkProblem));
                workbook.write(response.getOutputStream());
            } catch (Exception e) {
                log.error("", e);
            }

        } catch (Exception e) {
            log.error("", e);
        }
    }

    private List<RepetitionResult> getTcProRepResults(TrainClass trainClass, TrainHomeworkProblem trainHomeworkProblem) {
        List<RepetitionResult> repetitionResults = new ArrayList<>();
        List<TrainCommitRecord> trainCommitRecords = trainCommitRecordService.getByClassIdAndProblemId(trainClass.getId(), trainHomeworkProblem.getProblemId());
        List<TrainCommitRecord> trainCommitRecords1 = filterRecords(trainCommitRecords);

        for (int i = 0; i < trainCommitRecords1.size(); i++) {
            RepetitionResult result = new RepetitionResult();
            TrainCommitRecord record = trainCommitRecords1.get(i);

            result.setId(record.getUserId());
            result.setName(record.getUsername());
            result.setSubmitTime(TimeStamp2Date.timeStampToDate(record.getSubmitTime().getTime()));
            result.setRepRate(0.0);
            for (int j = 0; j < trainCommitRecords1.size(); j++) {
                if (j != i) {
                    double repRate = RepetitionRate.computeByLCS(trainCommitRecords1.get(i).getAnswer(), trainCommitRecords1.get(j).getAnswer());
                    if (repRate > result.getRepRate()) {
                        result.setrId(trainCommitRecords1.get(j).getUserId());
                        result.setrName(trainCommitRecords1.get(j).getUsername());
                        result.setrSubmitTime(TimeStamp2Date.timeStampToDate(trainCommitRecords1.get(j).getSubmitTime().getTime()));
                        result.setRepRate(new BigDecimal(repRate).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                    }
                }
            }
            repetitionResults.add(result);
        }
        return repetitionResults;
    }

    public static List<TrainCommitRecord> filterRecords(List<TrainCommitRecord> records) {
        // 创建一个Map来存储每个人最新提交的记录
        Map<Long, TrainCommitRecord> latestRecordsMap = new HashMap<>();

        // 遍历提交记录列表
        for (TrainCommitRecord record : records) {
            // 如果提交ID不为空且记录的创建时间比已存储的记录更新，或者之前没有存储过该用户的记录
            if (record.getSubmitId() != null &&
                    (!latestRecordsMap.containsKey(record.getUserId()) ||
                            record.getCreateTime().compareTo(latestRecordsMap.get(record.getUserId()).getCreateTime()) > 0)) {
                // 更新最新的提交记录
                latestRecordsMap.put(record.getUserId(), record);
            }
        }

        // 返回最新提交记录的列表
        return new ArrayList<>(latestRecordsMap.values());
    }
}
